/**
 *  Copyright 2010 Kyle O'Connor, Justin Arling, Mike Mercieca
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package edu.drexel.sd0910.ece01.aqmon.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

import edu.drexel.sd0910.ece01.aqmon.gui.wizard.WizardModel;
import edu.drexel.sd0910.ece01.aqmon.gui.wizard.WizardPanelDescriptor;
import edu.drexel.sd0910.ece01.aqmon.gui.wizard.impl.SummaryPanelDescriptor;
import edu.drexel.sd0910.ece01.aqmon.gui.wizard.impl.WelcomePanelDescriptor;
import edu.drexel.sd0910.ece01.aqmon.manager.Manager;

/**
 * Main GUI control - Controller component (MVC pattern)<br>
 * This class is the main controller for the system, handling all user actions,
 * and more specifically controls how the user traverses through the
 * <code>{@link edu.drexel.sd0910.ece01.aqmon.gui.wizard.Wizard Wizard}</code>.
 * 
 * @author Kyle O'Connor
 * 
 */
public class MainController extends WindowAdapter implements ActionListener {

	private final static Logger log = Logger.getLogger(MainController.class);

	private MainModel model;
	private MainView view;

	public MainController(MainModel aModel, MainView aView) {
		model = aModel;
		view = aView;

		// register control methods
		view.registerWindowControl(this);
		view.registerUIControl(this);
	}

	@Override
	public void windowClosing(WindowEvent we) {
		// system shutdown procedure
		int dialogReturnValue = view.showDialog("Are you sure you want to exit?");
		if (dialogReturnValue == JOptionPane.YES_OPTION) {
			log.debug("System shutting down...");
			model.setStatusText("System shutting down...");
			List<Manager> managers = model.getActiveManagers();
			for (Manager m : managers) {
				try {
					m.shutdown();
					log.debug(m + " shutdown");
				} catch (Exception e) {
					log.error("Error occurred during shutdown: " + e);
					// catch exception inside for loop so we report and move
					// onto next one
				}
			}
			// exit system after we've tried to shutdown all the managers
			System.exit(0);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		// check the button that was clicked
		if (e.getActionCommand().equals(GUICommands.EXIT))
			this.windowClosing(null); // probably unsafe but I know it will be okay here
		else if (e.getActionCommand().equals(GUICommands.CANCEL_BUTTON_ACTION_COMMAND))
			cancelButtonPressed();
		else if (e.getActionCommand().equals(GUICommands.BACK_BUTTON_ACTION_COMMAND))
			backButtonPressed();
		else if (e.getActionCommand().equals(GUICommands.NEXT_BUTTON_ACTION_COMMAND))
			nextButtonPressed();
	}

	private void nextButtonPressed() {
		WizardModel wizmodel = view.getWizard().getModel();
		WizardPanelDescriptor descriptor = wizmodel.getCurrentPanelDescriptor();
		// If it is a finishable panel, close down the dialog. Otherwise,
		// get the ID that the current panel identifies as the next panel,
		// and display it.
		Object nextPanelDescriptor = descriptor.getNextPanelDescriptor();

		if (nextPanelDescriptor instanceof WizardPanelDescriptor.FinishIdentifier) {
			// disable wizard now that we are finished
			view.getWizard().setNextFinishButtonEnabled(false);
			view.getWizard().setBackButtonEnabled(false);
			// hack to disable certain GUI elements on final summary panel
			if (descriptor instanceof SummaryPanelDescriptor) {
				((SummaryPanelDescriptor) descriptor).setGuiElementsEnabled(false);
			}
			log.debug("Start capture");
			model.setStatusText("Capturing air quality data...");
			model.setCaptureEnabled(true);
			//start tasks for all managers that implement the method
			List<Manager> managers = model.getActiveManagers();
			for (Manager m : managers) {
				m.startAllTasks();
			}
		} else {
			view.getWizard().setCurrentPanel(nextPanelDescriptor);
		}
	}

	private void backButtonPressed() {
		WizardModel wizmodel = view.getWizard().getModel();
		WizardPanelDescriptor descriptor = wizmodel.getCurrentPanelDescriptor();
		// Get the descriptor that the current panel identifies as the previous
		// panel, and display it.
		Object backPanelDescriptor = descriptor.getBackPanelDescriptor();
		view.getWizard().setCurrentPanel(backPanelDescriptor);
	}

	private void cancelButtonPressed() {
		int dialogReturnValue = view.showDialog("Are you sure you want to cancel?");
		if (dialogReturnValue == JOptionPane.YES_OPTION) {
			log.debug("Cancelled wizard");
			model.setCaptureEnabled(false);
			//stop tasks for all managers that implement the method
			List<Manager> managers = model.getActiveManagers();
			for (Manager m : managers) {
				m.stopAllTasks();
			}
			model.setStatusText("Air Quality Monitoring system ready...");
			view.getWizard().setCurrentPanel(WelcomePanelDescriptor.IDENTIFIER);
		}
	}

}
